<template>
    <!-- 加班申请界面 -->
    <div style="padding: 10px;">
        <el-row :gutter="24">
            <el-col :span="2">
                <div class="grid-content ep-bg-purple"><el-button type="primary" size="default"
                        style="width: 100px;" @click="add">提交申请</el-button>

                </div>
            </el-col>

            <el-col :span="2">
                <div class="grid-content ep-bg-purple">
                </div>
            </el-col>

            <el-col :span="12">
                <div class="grid-content ep-bg-purple">
                </div>
            </el-col>

            <el-col :span="4">
                <div class="grid-content ep-bg-purple-light">
                    <!-- 将搜索输入框与 searchKeyword 响应式变量进行双向绑定 -->
                    <el-input style="width: 180px" size="default" placeholder="搜索数据" v-model="overTimeNum"
                        @blur="loadOverTime" @keyup.enter="loadOverTime">
                        <template #prefix>
                            <el-icon class="el-input__icon">
                                <search />
                            </el-icon>
                        </template>
                    </el-input>
                </div>
            </el-col>

            <!-- <el-col :span="1">
                <div class="grid-content ep-bg-purple-light">
                    <a-tooltip content="筛选" position="bottom" background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click="dialog = true"><el-icon>
                                <Filter />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col>

            <el-col :span="1">
                <div class="grid-content ep-bg-purple-light"> <a-tooltip content="排序" position="bottom"
                        background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click=""><el-icon>
                                <Sort />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col> -->


            <el-col :span="2">
                <div class="grid-content ep-bg-purple-light"><a-tooltip content="刷新" position="bottom"
                        background-color="rgb(52, 145, 250)" mini>
                        <el-button size="default" @click="refresh"><el-icon>
                                <Refresh />
                            </el-icon></el-button>
                    </a-tooltip>
                </div>
            </el-col>
            <!--  -->
        </el-row>

        <el-row :gutter="24">
            <el-col :span="24">
                <el-table :data="overTimePage.records" style="height: 800px;" scrollbar-always-on
                    @row-click="handleRowClick">
                    <template v-for="(item, index) in overTime_columns" :key="index">
                        <el-table-column sortable v-if="!item.children" :label="item.label" :prop="item.prop">
                            <template #default="scope" v-if="item.prop === 'overtimeType'">
                                <el-tag :type="getOvertimeTypeTag(scope.row.overtimeType)" effect="dark">
                                    {{ scope.row.overtimeType }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column v-else :label="item.label">
                            <template v-for="(child, childIndex) in item.children" :key="childIndex">
                                <el-table-column :label="child.label" :prop="child.prop" />
                            </template>
                        </el-table-column>
                    </template>
                </el-table>

                <el-pagination @current-change="loadOverTime" v-model:currentPage="overTimePage.current"
                    :page-sizes="[2, 4, 6, 8, 10]" :page-size="overTimePage.size" :total="overTimePage.total"
                    background>
                </el-pagination>
            </el-col>
        </el-row>
    </div>

    <!--筛选  -->
    <el-drawer v-model="dialog" title="筛选" direction="rtl" class="demo-drawer">
        <div class="demo-drawer__content">
            <el-form :model="form" style="height: 600px;">
                <el-select v-model="Screening" placeholder="筛选" style="width: 360px" placement="bottom">
                    <template #label="{ label, value }">
                        <span style="font-weight: bold">{{ label }}</span>
                    </template>
                    <el-option v-for="item in FilterData" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>

            </el-form>
            <div class="demo-drawer__footer">
                <el-button @click="cancelForm">取消</el-button>
                <el-button type="primary" :loading="loading" @click="onClick">
                    {{ loading ? '提交中 ...' : '提交' }}
                </el-button>
            </div>
        </div>
    </el-drawer>

    <!--添加  -->
    <el-dialog align-center destroy-on-close title="加班申请" v-model="AddDisplay" width="780px">
        <overtimeApplication @ref-table="refTable"></overtimeApplication>
    </el-dialog>

    <!-- 详情页面 -->
    <el-dialog align-center destroy-on-close :title="user.employeeName + '-' + user.department.deptName"
        v-model="dialogVisible" width="780px">
        <overtimeApplicationDetails :overtimeApplicationDetails="selectedRow"></overtimeApplicationDetails>
    </el-dialog>

</template>

<script setup>
import { ref } from 'vue';
import request from '@/api/request';
import overtimeApplication from './overtimeApplication.vue';
import overtimeApplicationDetails from './overtimeApplicationDetails.vue';
const isVisible = ref(false) // 详情显示
const loading = ref(false) //抽屉加载
const dialog = ref(false); //抽屉

const overTimeNum = ref('')

// 获取session中的用户信息 - 需要解析JSON字符串
let user = JSON.parse(sessionStorage.getItem('user') || '{}');
console.log(user);

// 添加搜索关键词响应式变量，用于存储用户输入的搜索内容
const searchKeyword = ref('')

const dialogVisible = ref(false)
const selectedRow = ref({})

const handleRowClick = (row, event, column) => {
    selectedRow.value = row
    console.log(row)
    dialogVisible.value = true
}

// 数据
let overTimePage = ref({
    current: 1,
    size: 3,
    total: 0,
    records: []
})

let refTable = () => {
    AddDisplay.value = false;
    loadOverTime();
}

//刷新
const refresh = () => {
    request({
        url: "/overtimeApplication/page",
        method: "get",
        params: {
            current: 1,
            size: overTimePage.value.size
        }
    }).then(resp => {
        // 在数据加载后处理加班天数计算和年份提取
        if (resp.data && resp.data.records) {
            resp.data.records.forEach(record => {
                // 处理主记录的加班时长，计算并同步更新加班天数和加班总天数
                if (record.duration !== undefined) {
                    // 假设加班时长以小时为单位
                    const hours = parseFloat(record.duration);
                    if (!isNaN(hours)) {
                        let days = 0;
                        if (hours >= 8) {
                            days = 1;
                        } else if (hours >= 4) {
                            days = 0.5;
                        } else {
                            days = 0;
                        }
                        record.overTimeDay = days;
                        record.totalDay = days;
                    }
                }

                // 根据申请日期计算年份并赋值给归属年份
                if (record.applicationDate) {
                    // 从申请日期中提取年份
                    const date = new Date(record.applicationDate);
                    if (!isNaN(date.getTime())) {
                        record.attendanceYear = date.getFullYear();
                    }
                }
            });
        }
        overTimePage.value = resp.data;
        overTimeNum.value = '';
        console.log(resp.data);
    })
}

let loadOverTime = () => {
    request({
        url: "/overtimeApplication/page",
        method: "get",
        params: {
            current: overTimePage.value.current,
            size: overTimePage.value.size,
            applicationDate: overTimeNum.value
        }
    }).then(resp => {
        // 在数据加载后处理加班天数计算和年份提取
        if (resp.data && resp.data.records) {
            resp.data.records.forEach(record => {
                // 处理主记录的加班时长，计算并同步更新加班天数和加班总天数
                if (record.duration !== undefined) {
                    // 假设加班时长以小时为单位
                    const hours = parseFloat(record.duration);
                    if (!isNaN(hours)) {
                        let days = 0;
                        if (hours >= 8) {
                            days = 1;
                        } else if (hours >= 4) {
                            days = 0.5;
                        } else {
                            days = 0;
                        }
                        record.overTimeDay = days;
                        record.totalDay = days;
                    }
                }

                // 根据申请日期计算年份并赋值给归属年份
                if (record.applicationDate) {
                    // 从申请日期中提取年份
                    const date = new Date(record.applicationDate);
                    if (!isNaN(date.getTime())) {
                        record.attendanceYear = date.getFullYear();
                    }
                }
            });
        }
        overTimePage.value = resp.data;
        console.log(resp.data);
    })
}

// columns : 表头
const overTime_columns = ref([
    {
        label: '加班单号',
        prop: 'overtimeId',
    },
    {
        label: '申请日期',
        prop: 'applicationDate',
    },
    {
        label: '加班类型',
        prop: 'overtimeType',
    },
    {
        label: '归属年份',
        prop: 'attendanceYear',
    },
    {
        label: '加班明细',
        children: [
            {
                label: '加班开始时间',
                prop: 'startTime',
            },
            {
                label: '加班结束时间',
                prop: 'endTime',
            },
            {
                label: '星期',
                prop: 'week',
            },
            {
                label: '加班时长',
                prop: 'duration',
            },
            {
                label: '加班天数',
                prop: 'overTimeDay',
            },
            {
                label: '归属考勤周期',
                prop: 'attendanceCycle',
            },
        ],
    },
    {
        label: '加班总天数',
        prop: 'totalDay',
    },
    {
        label: '加班事由',
        prop: 'reason',
    },
    {
        label: '提交时间',
        prop: 'createdAt'
    },
    {
        label: '更新时间',
        prop: 'updatedAt'
    }
]);

// 根据加班类型返回 Tag 类型
const getOvertimeTypeTag = (overtimeType) => {
    // 你可以根据实际的加班类型值来定义不同类型
    switch (overtimeType) {
        case "工作日":
            return "primary";
        case "周末":
            return "success";
        case "法定节假日":
            return "danger";
        default:
            return "info";
    }
};

// 将搜索关键词转换为小写以实现不区分大小写的搜索
const keyword = searchKeyword.value.toLowerCase()

const form = ref();
const Screening = ref('') //筛选
const FilterData = ref([ //筛选数据
    { value: '全部', label: '全部' },
    { value: '待面试', label: '待面试' },
    { value: '待入职', label: '待入职' },
])
const onClick = () => {//抽屉提交
    loading.value = true
    setTimeout(() => {
        loading.value = false
        dialog.value = false
    }, 400)
}
//抽屉提交取消
const cancelForm = () => {
    loading.value = false
    dialog.value = false
}
// 获取当前数据
const handleClick = (row) => {
    console.log(row)
    isVisible.value = true
}
const AddDisplay = ref(false) // 添加显示
const Initiate = () => { //发起面试关闭
    AddDisplay.value = false
}
const add = () => { //添加
    AddDisplay.value = true

}

loadOverTime()
</script>

<style scoped></style>